import json
import random
import requests
from faker import Faker
from typing import List
import os

fake = Faker(['zh_CN'])  # 使用中文假数据

def load_init_json() -> dict:
    """加载初始JSON文件"""
    json_path = '/app/tests/create_table_init.json'
    with open(json_path, "r") as file:
        return json.load(file)

def generate_fake_user() -> dict:
    """生成一个假用户数据"""
    # 可选的角色
    available_roles = ["base", "test", "normal"]
    # 随机选择1-3个角色
    selected_roles = random.sample(available_roles, random.randint(1, len(available_roles)))
    
    return {
        "username": fake.unique.user_name()[:7],  # 确保用户名不超过20字符
        "password": "test",  # 按要求固定为test
        "user_phone": fake.phone_number()[:11],
        "user_email": fake.email(),
        "full_name": fake.name(),
        "user_status": random.choice([0, 1]),
        "sex": random.choice([0, 1, 2]),
        "header_img": random.choice([f"/static/profile/profile-{i}.png" for i in range(1, 7)]),
        "remarks": fake.sentence()[:30],  # 限制备注长度
        "role_list": [{"role_name": role} for role in selected_roles]
    }

def create_users(base_url: str, num_users: int = 10):
    """创建用户"""
    url = f"{base_url}/api/v1/user/create_any"
    headers = {
        'Content-Type': 'application/json'
    }
    
    # 首先发送初始JSON数据
    try:
        init_data = load_init_json()
        response = requests.post(url, json=init_data, headers=headers)
        print(f"初始用户创建结果: {response.status_code}")
        print(response.json())
    except Exception as e:
        print(f"创建初始用户失败: {str(e)}")

    # 创建假用户数据
    success_count = 0
    for i in range(num_users):
        try:
            fake_user = generate_fake_user()
            response = requests.post(url, json=fake_user, headers=headers)
            if response.status_code == 200:
                success_count += 1
                print(f"成功创建用户 {i+1}: {fake_user['username']}")
            else:
                print(f"创建用户 {i+1} 失败: {response.status_code}")
                print(response.json())
        except Exception as e:
            print(f"创建用户 {i+1} 时发生错误: {str(e)}")
    
    print(f"\n总结: 成功创建 {success_count} 个用户")

if __name__ == "__main__":
    BASE_URL = "http://172.16.1.188:18000"  # 替换为实际的基础URL
    create_users(BASE_URL, num_users=20)  # 创建100个假用户 